package com.zw.yzk.kabu.view.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.widget.EditText;

import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.adapter.PublishImageListAdapter;
import com.zw.yzk.kabu.base.BaseActivity;
import com.zw.yzk.kabu.constant.ActivityConstant;
import com.zw.yzk.kabu.data.cache.db.DataBaseManager;
import com.zw.yzk.kabu.data.cache.db.User;
import com.zw.yzk.kabu.domain.interactor.DefaultOnNext;
import com.zw.yzk.kabu.internal.component.DaggerRefundComponent;
import com.zw.yzk.kabu.internal.module.ActivityModule;
import com.zw.yzk.kabu.internal.module.CancelOrderModule;
import com.zw.yzk.kabu.management.LoadingDialogManager;
import com.zw.yzk.kabu.management.ToastManager;
import com.zw.yzk.kabu.management.ToolbarBuilder;
import com.zw.yzk.kabu.model.PublishImageModel;
import com.zw.yzk.kabu.presenter.RefundPresenter;
import com.zw.yzk.kabu.utils.ImageUtils;
import com.zw.yzk.kabu.view.view.RefundView;

import java.io.File;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import rx.Observable;

/**
 * Created by zhanwei on 2017/2/11.
 */

public class RefundActivity extends BaseActivity implements RefundView {

    @Bind(R.id.refund_remark)
    public EditText refundRemark;
    @Bind(R.id.images)
    public RecyclerView imageList;

    @Inject
    RefundPresenter presenter;
    public PublishImageListAdapter adapter;

    @Override
    public int getLayoutId() {
        return R.layout.activity_refund;
    }

    @Override
    public void iniToolbar(BaseActivity activity) {
        ToolbarBuilder
                .createBuilder(this)
                .setTitle(getResources().getString(R.string.refund))
                .build();
    }

    @Override
    public void initComponent() {
        DaggerRefundComponent.builder()
                .applicationComponent(getApplicationComponent())
                .activityModule(new ActivityModule(this))
                .cancelOrderModule(new CancelOrderModule())
                .build()
                .inject(this);
        presenter.setView(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getUploadImageToken();
        initRecyclerView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.destroy();
        }
    }

    @Override
    public void refundSuccess() {
        Observable.timer(500, TimeUnit.MILLISECONDS)
                .subscribe(new DefaultOnNext<Long>() {
                    @Override
                    public void call(Long var1) {
                        finish();
                    }
                });
    }

    @OnClick(R.id.submit_apply)
    public void submitApply() {
        if (TextUtils.isEmpty(refundRemark.getText().toString())) {
            ToastManager.getInstance().showToast(this, getResources().getString(R.string.reason_could_not_be_null));
        } else if (adapter.getImageList().isEmpty()) {
            ToastManager.getInstance().showToast(this, getResources().getString(R.string.please_select_refund_image));
        } else {
            LoadingDialogManager.getInstance().showLoadingDialog(this);
            refund();
        }
    }

    /**
     * 初始化recyclerview
     */
    private void initRecyclerView() {
        //设置为网格显示
        imageList.setLayoutManager(new GridLayoutManager(this, 3, LinearLayoutManager.VERTICAL, false));
        //设置默认动画
        imageList.setItemAnimator(new DefaultItemAnimator());
        adapter = new PublishImageListAdapter(null, 3);
        //设置点击+号选择图片
        adapter.setOnAddImageClickedListener(new PublishImageListAdapter.OnImageClickedListener() {
            @Override
            public void onAddImageClicked() {
                if (adapter.getItemCount() >= 4) {
                    return;
                }
                selectImage();
            }

            @Override
            public void onImageContentClicked() {
            }
        });
        imageList.setAdapter(adapter);
    }

    /**
     * 打开图片选择器
     */
    public void selectImage() {
        //配置功能
        FunctionConfig functionConfig = new FunctionConfig.Builder()
                .setEnableCamera(false)
                .setEnableEdit(false)
                .setEnableCrop(false)
                .setEnableRotate(true)
                .setCropSquare(true)
                .setEnablePreview(true)
                .setForceCrop(false)
                .build();
        GalleryFinal.openGallerySingle(ActivityConstant.OPEN_GALLERY, functionConfig, new GalleryFinal.OnHandlerResultCallback() {
            @Override
            public void onHandlerSuccess(int requestCode, List<PhotoInfo> resultList) {
                if (ActivityConstant.OPEN_GALLERY == requestCode) {
                    if (resultList.size() <= 0) {
                        ToastManager.getInstance().showToast(RefundActivity.this, getResources().getString(R.string.read_file_error));
                    } else {
                        String url = ImageUtils.compress(RefundActivity.this, new File(resultList.get(0).getPhotoPath()));
                        PublishImageModel model = new PublishImageModel();
                        model.setContentPath(url);
                        model.setRemark(null);
                        adapter.add(model);
                    }
                }
            }

            @Override
            public void onHandlerFailure(int requestCode, String errorMsg) {
                ToastManager.getInstance().showToast(RefundActivity.this, errorMsg + "(" + requestCode + ")");
            }
        });
    }

    /**
     * 退货
     */
    private void refund() {
        presenter.refund(getIntent().getStringExtra(ActivityConstant.REFUND_ORDER_ID),
                refundRemark.getText().toString(), adapter.getImageList());
    }

    /**
     * 获取七牛图片上传token
     */
    public void getUploadImageToken() {
        User user = DataBaseManager.getInstance().getLoginUser();
        if (user == null || !user.isLogin()) {
            return;
        }
        presenter.getUploadImageToken();
    }
}
